<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        ref="fcipt"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-model.trim="kw"
        @input="iptFn"
        @keydown.enter="kw.length !== 0 && gotosearchresultpage(kw)"
      />
    </div>
    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="kw.length !== 0">
      <div
        class="sugg-item"
        v-for="(item, index) in suggestionlist"
        :key="index"
        v-html="lightFn(item, kw)"
        @click="gotosearchresultpage(item)"
      ></div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="delFn" />
        </template>
      </van-cell>
      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(item, index) in history"
          :key="index"
          @click="gotosearchresultpage(item)"
          @touchstart="touchstartFn(index)"
          @touchmove="touchmoveFn"
          @touchend="touchendFn"
          @contextmenu.prevent
          @selectstart.prevent
          >{{ item }}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
// 引入联想菜单组件
import { getsuggestionAPI } from '../../api/search'
// 引入关键字高亮的组件
import { lightFn } from '../../utils/str'
// 引入提示框组件
import { Dialog, Toast } from 'vant'
export default {
  name: 'searchpage',
  data () {
    return {
      kw: '', // 搜索关键字
      time: null, // 定时器
      suggestionlist: [], // 联想菜单数组
      lightFn, // 高亮关键字的变量
      history: JSON.parse(localStorage.getItem('searchList')) || [] // 搜索历史
    }
  },
  methods: {
    // input触发的事件
    iptFn () {
      clearTimeout(this.time)
      this.time = setTimeout(async () => {
        if (this.kw.length === 0) {
          this.suggestionlist = []
          return
        }
        const res = await getsuggestionAPI({ q: this.kw })
        const arr = res.data.options.map((item) => {
          return item.replace(/ /gi, '')
        })
        this.suggestionlist = arr
      }, 1000)
    },
    // 跳转的公共方法
    gotosearchresultpage (msg) {
      // 不允许相同的数据重复添加
      if (!this.history.includes(msg)) {
        this.history.push(msg)
      }
      // 存储到本地
      localStorage.setItem('searchList', JSON.stringify(this.history))

      // 跳转页面前清空 输入框
      this.kw = ''

      // 延迟跳转否则无法存储本地
      setTimeout(() => {
        this.$router.push({
          name: 'gotoFn',
          params: {
            keyword: msg
          }
        })
      })
    },
    // 删除历史记录
    async delFn () {
      // 没有历史记录弹出提示
      if (this.history.length === 0) return Toast('没有历史记录')
      try {
        await Dialog.confirm({
          message: '确认删除吗?'
        })
        localStorage.removeItem('searchList')
        this.history = []
      } catch (e) {}
    },
    // 长按删除历史记录
    touchstartFn (i) {
      this.timer = setTimeout(async () => {
        try {
          await Dialog.confirm({
            message: '确认删除该历史记录吗?'
          })
          this.history.splice(i, 1)
          // 存储到本地
          localStorage.setItem('searchList', JSON.stringify(this.history))
        } catch (e) {}
      }, 1000)
    },
    touchmoveFn () {
      // 手指移动关闭定时器
      clearTimeout(this.timer)
    },
    touchendFn () {
      // 手指抬起关闭定时器
      clearTimeout(this.timer)
    }
  },
  // 每次都要输入框聚焦
  activated () {
    this.$refs.fcipt.querySelector('input[type="search"]').focus()
  }

}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
